import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ChatProvider, WebSocketProvider } from './contexts';
import { LoginPage, ChatPage } from './pages';
import { useToast } from './hooks';
import { ToastContainer } from './components/UI';

export default function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [username, setUsername] = useState('');
  const { showToast } = useToast();
  // Toast功能通过ToastContainer组件提供
  
  const handleLogin = (name: string) => {
    setUsername(name);
    setIsLoggedIn(true);
    showToast(`欢迎 ${name}！`, 'success');
  };
  
  const handleLogout = () => {
    setIsLoggedIn(false);
    setUsername('');
    showToast('已退出聊天室', 'info');
  };
  
  return (
    <Router>
      <WebSocketProvider>
        <ChatProvider>
          <div className="App" data-app="react-chat">
            <Routes>
              <Route
                path="/login"
                element={
                  isLoggedIn ? (
                    <Navigate to="/chat" replace />
                  ) : (
                    <LoginPage onLogin={handleLogin} />
                  )
                }
              />
              <Route
                path="/chat"
                element={
                  isLoggedIn ? (
                    <ChatPage username={username} onLogout={handleLogout} />
                  ) : (
                    <Navigate to="/login" replace />
                  )
                }
              />
              <Route
                path="/"
                element={
                  <Navigate to={isLoggedIn ? "/chat" : "/login"} replace />
                }
              />
            </Routes>
            <ToastContainer />
          </div>
        </ChatProvider>
      </WebSocketProvider>
    </Router>
  );
}


